using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;

namespace AviagePortal.Features.CreateCMSStructure
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("d0c23a6b-3314-48d6-bfed-9aee2b455fd9")]
    public class CreateCMSStructureEventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite siteCollection = properties.Feature.Parent as SPSite;
            if (siteCollection != null)
            {
                SPWeb rootWeb = siteCollection.OpenWeb();
                var  listtemplates = siteCollection.GetCustomListTemplates(rootWeb);               
                /*string[] listNames = { "Career", "CompanyHistory", "CompanyIntroduce", "ContactUs", "GlobalSettings", "HomePage", 
                                         "LeaderShipDetail", "LeaderShipMain", "MediaCenter", "MediaDetail", "NewsDetail", "NewsMain", 
                                         "Opportunities", "OurLife", "PartnerShip", "Product", "Service", "SiteContents", "SiteData",
                                          "SocialDuty", "Training", "ContactInformation"};*/

                string[] listNames = { "Career", "CompanyHistory", "CompanyIntroduce", "ContactUs", "GlobalSettings", "HomePage", 
                                         "LeaderShipDetail", "LeaderShipMain", "MediaCenter", "MediaDetail", "NewsDetail", "NewsMain", 
                                         "Opportunities", "OurLife", "PartnerShip", "Product", "Service", "SiteContents", "SiteData",
                                          "SocialDuty", "Training", "ContactInformation", "Terms", "ContactInformationPage","SiteMap" , "ApproveRecords"};

                foreach (var listName in listNames)
                {
                    var template = listtemplates[listName];
                    CreateListWithTemplate(listName, template, rootWeb);
                }

                // Enable the approval progress for SiteData
                SPList siteData = rootWeb.Lists["SiteData"];
                siteData.EnableModeration = true;
                if (!siteData.HasUniqueRoleAssignments)
                {
                    siteData.BreakRoleInheritance(false, true);
                }

                siteData.Update();

                // http://firstblogofvarun.blogspot.com/2009/06/how-to-add-spgroup-to-site-collection.html
                // rootWeb.Groups.
                SPGroup editorGroup = null;
                SPGroup approverGroup = null;
                try
                {
                    editorGroup = rootWeb.SiteGroups["AviagePortalEditor"];
                }
                catch (Exception ex)
                {
                    rootWeb.SiteGroups.Add("AviagePortalEditor", rootWeb.CurrentUser, rootWeb.CurrentUser, "AviagePortal Editor");
                    editorGroup = rootWeb.SiteGroups["AviagePortalEditor"];
                }


                try
                {
                    approverGroup = rootWeb.SiteGroups["AviagePortalApprover"];
                }
                catch (Exception ex)
                {
                    rootWeb.SiteGroups.Add("AviagePortalApprover", rootWeb.CurrentUser, rootWeb.CurrentUser, "AviagePortal Approver");
                    approverGroup = rootWeb.SiteGroups["AviagePortalApprover"];
                }

                // Create two groups (content editor group and content approval group)              
                SPRoleAssignment roleAssignment = new SPRoleAssignment(editorGroup);
                SPRoleDefinition roleDefinition = rootWeb.RoleDefinitions["Contribute"];
                roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
                siteData.RoleAssignments.Add(roleAssignment);


                SPRoleAssignment roleAssignmentForApprover = new SPRoleAssignment(approverGroup);
                SPRoleDefinition roleDefinitionForApprover = rootWeb.RoleDefinitions["Design"];
                roleAssignmentForApprover.RoleDefinitionBindings.Add(roleDefinitionForApprover);
                siteData.RoleAssignments.Add(roleAssignmentForApprover);

                
                roleAssignment = new SPRoleAssignment(editorGroup);
                roleDefinition = rootWeb.RoleDefinitions["Contribute"];
                roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
                rootWeb.RoleAssignments.Add(roleAssignment);


                roleAssignment = new SPRoleAssignment(approverGroup);
                roleDefinition = rootWeb.RoleDefinitions["Contribute"];
                roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
                rootWeb.RoleAssignments.Add(roleAssignment);

                siteData.Update();

                // Add short description for news detail
                SPList newsDetail = rootWeb.Lists["NewsDetail"];
                if (newsDetail != null && !newsDetail.Fields.ContainsFieldWithStaticName("ShortDescription"))
                {
                    string shortDescription = newsDetail.Fields.Add("ShortDescription", SPFieldType.Note, true);
                    var shortDescriptionFiled = newsDetail.Fields[shortDescription] as SPFieldMultiLineText;
                    shortDescriptionFiled.RichText = false;
                    shortDescriptionFiled.Update();
                }

                // BackgroundPicture Service
                SPList serviceList = rootWeb.Lists["Service"];
                if (serviceList != null && !serviceList.Fields.ContainsFieldWithStaticName("BackgroundPicture"))
                {
                    string backgroundPicture = serviceList.Fields.Add("BackgroundPicture", SPFieldType.Text, true);
                }

            //    // original
            //    if (serviceList != null && !serviceList.Fields.ContainsFieldWithStaticName("OriginalBackgroundPicture"))
            //    {
            //        string originalBackgroundPicture = serviceList.Fields.Add("OriginalBackgroundPicture", SPFieldType.Text, true);
            //    }

                // Added Background for Opportunities
                SPList opportunitiesList = rootWeb.Lists["Opportunities"];
                if (!opportunitiesList.Fields.ContainsFieldWithStaticName("BackgroundPicture"))
                {
                    opportunitiesList.Fields.Add("BackgroundPicture", SPFieldType.Text, false);
                }
            }
        }

        private void CreateListWithTemplate(string listName,SPListTemplate template, SPWeb web )
        {
            if (!ContainsList(web.Lists, listName))
            {
                var guid = web.Lists.Add(listName, listName, template);           
            }
        }

        private bool ContainsList(SPListCollection listCollection, string listName)
        {
            foreach (SPList list in listCollection)
            {
                if (list.Title == listName)
                {
                    return true;
                }
            }

            return false;
        }

        // Uncomment the method below to handle the event raised before a feature is deactivated.

        //public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}
